using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace SqlTools.CodeGenerator.Data
{
	public enum MethodType
	{
		SelectSingle,
		SelectMultiple,
		Insert,
		Update,
		Delete,
		Custom
	}

	public class Method
	{
		protected string _methodName;
		protected List<MethodParameter> _parameters;
		protected Table _table;
		protected MethodType _type;
		protected string _storedProcedureName;

		public Method(string name, Table table, MethodType type)
		{
			_methodName = name;
			_table = table;
			_type = type;
			_parameters = new List<MethodParameter>();
			_storedProcedureName = "";
		}

		public string MethodName
		{
			get { return _methodName; }
			set { _methodName = value; }
		}

		public List<MethodParameter> Parameters
		{
			get { return _parameters; }
		}

		public Table Table
		{
			get { return _table; }
		}

		public MethodType Type
		{
			get { return _type; }
			set { _type = value; }
		}

		public string StoredProcedureName
		{
			get { return _storedProcedureName; }
			set { _storedProcedureName = value; }
		}

		public void SaveXml(XmlDocument doc, XmlElement parent)
		{
			XmlElement el = CreateXmlElement(doc);
			parent.AppendChild(el);

			XmlElement xmlParameters = doc.CreateElement("Parameters");
			el.AppendChild(xmlParameters);

			foreach ( MethodParameter param in _parameters )
			{
				param.SaveXml(doc, xmlParameters);
			}
		}

		public XmlElement CreateXmlElement(XmlDocument doc)
		{
			XmlElement el = doc.CreateElement("Method");

			el.Attributes.Append(doc.CreateAttribute("MethodName")).Value = _methodName;
			el.Attributes.Append(doc.CreateAttribute("Type")).Value = _type.ToString();
			el.Attributes.Append(doc.CreateAttribute("StoredProcedureName")).Value = _storedProcedureName;

			return el;
		}

		public void LoadXml(XmlElement xmlMethod)
		{
			_methodName = xmlMethod.GetAttribute("MethodName");
			_storedProcedureName = xmlMethod.GetAttribute("StoredProcedureName");

			string typename = xmlMethod.GetAttribute("Type");
			_type = (MethodType)Enum.Parse(typeof(MethodType), typename);

			XmlNodeList nodes = xmlMethod.GetElementsByTagName("Parameters");
			if ( nodes.Count > 0 )
			{
				LoadParametersXml(nodes[0] as XmlElement);
			}
		}

		protected void LoadParametersXml(XmlElement xmlElement)
		{
			foreach ( XmlNode node in xmlElement.ChildNodes )
			{
				if ( node.NodeType == XmlNodeType.Element )
				{
					XmlElement xmlParameter = node as XmlElement;
					MethodParameter param = new MethodParameter("", this, null);

					param.LoadXml(xmlParameter);

					_parameters.Add(param);
				}
			}
		}

		public override string ToString()
		{
			string name = "";
			if ( _table != null )
				name = _table.TableName + ".";

			return  name + _methodName;
		}
	}
}
